package com.h2wallet.newsapi.modular.news.service.impl;

import com.h2wallet.newsapi.modular.basic.service.impl.EntityServiceImpl;
import com.h2wallet.newsapi.modular.news.entity.ArticleEntity;
import com.h2wallet.newsapi.modular.news.entity.ArticleTypeEntity;
import com.h2wallet.newsapi.modular.news.repository.ArticleRepository;
import com.h2wallet.newsapi.modular.news.repository.ArticleTypeRepository;
import com.h2wallet.newsapi.modular.news.service.ArticleService;
import com.h2wallet.newsapi.modular.news.vo.Article;
import com.h2wallet.newsapi.modular.news.vo.ArticleType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class ArticleServiceImpl extends EntityServiceImpl<ArticleEntity, Article, Integer> implements ArticleService {

    private final ArticleRepository articleRepository;
    private final ArticleTypeRepository articleTypeRepository;

    public ArticleServiceImpl(ArticleRepository articleRepository,
                              ArticleTypeRepository articleTypeRepository) {
        super(articleRepository);
        this.articleRepository = articleRepository;
        this.articleTypeRepository = articleTypeRepository;
    }

    @Override
    public List<Article> findAllByTypeId(int id, int page, int size){
        Pageable pageable = PageRequest.of(page, size);
        return poListToVoList(articleRepository.findAllByTypeIdAndDeletedFalse(id, pageable));
    }

    @Override
    public int countByTypeId(int id) {
        return articleRepository.countByTypeIdAndDeletedFalse(id);
    }

    @Override
    protected Article poToVo(ArticleEntity po) {
        Article article = super.poToVo(po);
        Optional<ArticleTypeEntity> optionalArticleType = articleTypeRepository.findById(po.getTypeId());
        optionalArticleType.ifPresent(articleTypeEntity -> article.setTypeName(articleTypeEntity.getName()));//java8判断空方法

        article.setCreateTime(po.getCreateTime().getTime());
        return article;
    }
}
